angular.module('casher.services', [])
/**
 * 销售数据
 * @param  {String}
 * @param  {Function} callback  scope 将订阅绑定到根作用域用于共享
 * @return {object} 返回公共方法
 */
.factory('SalesService',function(){

  var getSaleOrdersSub = function(scope){
    return scope.subscribe('sale_orders');
  };

  return {
    /**
     * 总销售额
     * @param  {callback} callback 回调函数，赋值操作
     */
    analytic : function(scope,feild,callback){
      scope.helpers({
        sale_orders: function() {
          return SaleOrders.find();
        }
      });

      scope.autorun(function() {
        if(getSaleOrdersSub(scope).ready() && scope.sale_orders){
          var anaSale={totalSale:0,orderCount:0,productCount:0,loaded:false}; //,totalMargin:0,totalMarginRatio:0

          if(scope.sale_orders.length){
            scope.sale_orders.forEach(function(order){
              anaSale.totalSale+=order.amount;
              anaSale.orderCount++;
              anaSale.productCount+=order.total_count;
            });
          }
          anaSale.loaded = true; 
          callback(anaSale);
        }
      });
    }
  };
});
